import React, { useEffect, useRef, useState } from 'react';
import { Button, Input, InputRef, Pagination, PaginationProps, Popconfirm, Space, Table, Tag, message } from 'antd';
import { EditOutlined, DeleteOutlined, SearchOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import type { ColumnsType, ColumnType } from 'antd/es/table';
import style from './index.module.scss'
import { useRouter } from 'next/router'
import { FilterConfirmProps } from 'antd/es/table/interface';
import { getLayout } from '@/components/Layout'
import { deleteNote, getNoteList } from "@/api/programmingNotes";

interface DataType {
  id: string;
  key: string;
  title: string;
  author: string;
  createTime: string;
  modifyTime: string;
}

type DataIndex = keyof DataType;

const ProgrammingNotes: React.FC = () => {
  const isFistRender = useRef(true)
  const [messageApi, contextHolder] = message.useMessage();

  const router = useRouter();
  const showTotal: PaginationProps['showTotal'] = (total) => `共 ${total} 条`;

  const [searchContent, setSearchContent] = useState({
    title: '',
    author: '',
    order: '',
  })
  const searchInput = useRef<InputRef>(null);

  const [noteList, setNoteList] = useState([])
  const [total, setTotal] = useState(0)
  const [pageNo, setPageNo] = useState(1)
  const [pageSize, setPageSize] = useState(10)

  const getColumnSearchProps = (dataIndex: DataIndex, title: string): ColumnType<DataType> => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }} onKeyDown={(e) => e.stopPropagation()}>
        <Input
          ref={searchInput}
          placeholder={`搜索${title}`}
          value={selectedKeys[0]}
          onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => handleSearch(selectedKeys as string[], confirm, dataIndex)}
          style={{ marginBottom: 8, display: 'block' }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys as string[], confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{ width: 90 }}
          >
            搜索
          </Button>
          <Button
            onClick={() => clearFilters && handleReset(clearFilters)}
            size="small"
            style={{ width: 90 }}
          >
            重置
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered: boolean) => (
      <SearchOutlined style={{ color: filtered ? '#1677ff' : undefined }} />
    ),
    onFilterDropdownOpenChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current?.select(), 100);
      }
    },
  });

  const columns: ColumnsType<DataType> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: '5%',
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: '40%',
      ...getColumnSearchProps('title', '标题'),
      render: (_, record) => {
        return (
          <span className='title-header' onClick={() => gotoDetail(record.id)}>{record.title}</span>
        )
      },
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
      width: '10%',
      ...getColumnSearchProps('author', '作者'),
    },
    {
      title: '发布时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: '15%',
      sorter: (a, b, sortOrder) => {
        const orderType = sortOrder?.replace('end', '')
        setSearchContent({
          ...searchContent,
          order: `createTime:${orderType}`
        });
        return 0
      },
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '修改时间',
      dataIndex: 'modifyTime',
      key: 'modifyTime',
      width: '15%',
      sorter: (a, b, sortOrder) => {
        const orderType = sortOrder?.replace('end', '')
        setSearchContent({
          ...searchContent,
          order: `modifyTime:${orderType}`
        });
        return 0
      },
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '操作',
      width: '30%',
      dataIndex: 'action',
      key: 'action',
      render: (_, record) => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              className='edit-btn'
              onClick={() => handleEdit(record.id)}
              icon={<EditOutlined />}
            >编辑
            </Button>
            <Popconfirm
              title={record.title}
              description="是否确认删除此笔记?"
              icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
              onConfirm={() => handleDelete(record.id)}
            >
              <Button
                type="text"
                className='delete-btn'
                icon={<DeleteOutlined />}
              >删除</Button>
            </Popconfirm>
          </Space>
        )
      },
    },
  ];

  useEffect(() => {
    if (isFistRender.current) {
      getNoteListByQuery()
      isFistRender.current = false
    } else {
      getNoteListByQuery()
      listScrollTop()
    }
  }, [pageNo, pageSize, JSON.stringify(searchContent)])


  // 获取列表
  const getNoteListByQuery = () => {
    const params = {
      pageNo,
      pageSize,
      searchContent
    }
    getNoteList(params).then(res => {
      const {
        list = [],
        total = 0
      } = res?.data?.body ?? {}

      setNoteList(list)
      setTotal(total)
    })
  }

  // 列表滚动到顶部
  const listScrollTop = () => {
    const scrollDom = document.querySelector('.ant-layout-content');
    if (scrollDom) scrollDom.scrollTop = 0
  }

  // 跳转到编辑页面
  const handleEdit = (id: string) => {
    router.push({
      pathname: '/system/programmingNotes/form',
      query: { id }
    },)
  }

  // 跳转到详情页面
  const gotoDetail = (id: string) => {
    router.push({
      pathname: '/system/programmingNotes/detail',
      query: { id }
    },)
  }

  // 删除笔记
  const handleDelete = (id: string) => {
    deleteNote({ id }).then(res => {
      const {
        code = '000'
      } = res?.data ?? {}
      if (code === '200') {
        messageApi.success('删除成功！');
        getNoteListByQuery()
      }
    })
  }

  // 跳转到新增页面
  const handleCreate = () => {
    router.push({
      pathname: '/system/programmingNotes/form'
    })
  }

  // 搜索笔记
  const handleSearch = (
    selectedKeys: string[],
    confirm: (param?: FilterConfirmProps) => void,
    dataIndex: DataIndex,
  ) => {
    confirm();
    setSearchContent({
      ...searchContent,
      [dataIndex]: selectedKeys[0]
    });
  };

  // 重置搜索内容
  const handleReset = (clearFilters: () => void) => {
    clearFilters();
    setSearchContent({
      title: '',
      author: '',
      order: '',
    });
  };

  return (
    <>
      {contextHolder}
      <div className={style.programming_notes}>
        <Button type="primary" className='add-btn' onClick={handleCreate}>新建</Button>
        <Table
          columns={columns}
          pagination={false}
          dataSource={noteList}
          rowKey={item => item.id}
        />
        <Pagination
          className="pagination"
          showSizeChanger
          showQuickJumper
          showTotal={showTotal}
          current={pageNo}
          total={total}
          onChange={(page: number) => setPageNo(page)}
          onShowSizeChange={(page: number, size: number) => {
            setPageNo(page)
            setPageSize(size)
          }}
        />
      </div>
    </>
  )
};

export default getLayout(ProgrammingNotes);
